import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import {Message} from 'element-ui'

// axios.defaults.baseURL = url.baseURL
axios.defaults.withCredentials = true
// 添加一个请求拦截器
axios.interceptors.request.use(config => {
  if (config.method === 'post') {
    for (let i in config.data) {
      if (i === 'lhcId' && config.data[i] === 0) {
        config.data[i] = undefined
      }
      if (i === 'lhcWxId' && config.data[i] === 0) {
        config.data[i] = undefined
      }
      if (i === 'lotteryId' && config.data[i] > 1000) {
        config.data[i] = 1
      }
    }
    config.data = qs.stringify(config.data, {indices: false})
  }
  // if (config.pathVar) {
  //   config.url = config.url + '/' + config.pathVar
  // }
  return config
}, error => {
  return Promise.reject(error)
})

// 添加一个响应拦截器
axios.interceptors.response.use(response => {
  return new Promise((resolve, reject) => {
    if (response.data.code === '000000') {
      resolve(response.data)
    } else if (response.data.code === '000100') {
      getIsNull(response.data.msg)
      window.sessionStorage.setItem("loginStatus", '')
      reject(response.data)
    } else if (response.data.code === '500') {
      reject(response.data)
      getIsNull(response.data.msg)
    } else {
      reject(response.data)
      getIsNull(response.data.msg)
    }
  })
}, (error) => {
  console.log(error.response)
  getIsNull(error.response.data.msg)
})

const getIsNull = (mes) => {
  if (mes === '') {
    Message.error('未知错误')
  } else {
    Message.error(mes)
  }
}
export default axios
